//
//  RealViewController.m
//  markmap
//
//  Created by 甘世清 on 2024/6/11.
//

#import "RealViewController.h"
#import "RealCollectionViewCell.h"
#import "ViewController.h"
#import "RealPopView.h"
@interface RealViewController ()<UIImagePickerControllerDelegate,UINavigationControllerDelegate,UICollectionViewDelegate,UICollectionViewDataSource>
@property (nonatomic , strong) SQCustomButton * addImage;
@property (nonatomic , strong) NSString * imageUrl;
@property (nonatomic, strong) UIImagePickerController *imagePickerVc;
@property (nonatomic, strong) SQCustomButton * btn;
@property (nonatomic , assign) BOOL isXieyi;
@end

@implementation RealViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.zx_navTitle = SQNSLocalString(@"真人认证");
    self.view.backgroundColor = UIColor.blackColor;
    // Do any additional setup after loading the view.
    WS(weakSelf);
    NSString * valuue = [Manager SQ_stringForKey:@"userinfo_switch"];
    if (![valuue isEqualToString:@"1"]) {
        return;
    }
    if (self.isInfo) {
        [self zx_setRightBtnWithText:SQNSLocalString(@"跳过") clickedBlock:^(ZXNavItemBtn * _Nonnull btn) {
           UINavigationController *nav = [[UINavigationController alloc] initWithRootViewController:[[ViewController alloc]init] ];
            weakSelf.view.window.rootViewController = nav;
        }];
        self.zx_navLeftBtn.hidden = YES;
    }
}

- (void)SQ_UIViewForSelfView{
    
    [self.collectionView registerClass:[RealCollectionViewCell class] forCellWithReuseIdentifier:@"RealCollectionViewCell"];
    self.collectionView.alwaysBounceVertical = NO;
    UICollectionViewFlowLayout* flowLayout = [[UICollectionViewFlowLayout alloc]init];
    flowLayout.scrollDirection = UICollectionViewScrollDirectionHorizontal;
    self.collectionView.collectionViewLayout = flowLayout;
    [self.view addSubview:self.collectionView];
    self.collectionView.dataSource = self;
    self.collectionView.delegate = self;
    [self.collectionView mas_makeConstraints:^(MASConstraintMaker *make) {
          make.top.equalTo(self.zx_navBar.mas_bottom).offset(10);
          make.left.right.equalTo(self.view);
          make.height.mas_equalTo(250);
    }];
    [self.collectionView reloadData];
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        [self.collectionView scrollToItemAtIndexPath:[NSIndexPath indexPathForItem:1 inSection:0] atScrollPosition:UICollectionViewScrollPositionCenteredHorizontally animated:NO];
    });
    
    
    [self.view addSubview:self.addImage];
    [self.addImage mas_makeConstraints:^(MASConstraintMaker *make) {
            make.centerX.equalTo(self.view);
            make.width.mas_equalTo(SCREEN_WIDETH-120);
            make.top.equalTo(self.collectionView.mas_bottom).offset(10);
            make.bottom.equalTo(self.view.mas_bottom).offset(-FootHeight-120);
    }];
    WS(weakSelf);
    [self.addImage setTouchBlock:^(SQCustomButton * _Nonnull button) {
        [weakSelf SQ_addImageButtonClick];
    }];
    
    UILabel * num5 = [[UILabel alloc]init];
    num5.text = SQNSLocalString(@"认证结果如与性别不符，将强制修改性别");
    num5.font = FONT_MEDIUM(14);
    num5.textColor = SQColor(@"#C79B58");
    [self.view addSubview:num5];
    [num5 mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.equalTo(self.view);
        make.top.equalTo(self.addImage.mas_bottom).offset(20);
    }];
    
    self.btn = [[SQCustomButton alloc]initType:SQCustomButtonTopImageType imageSize:CGSizeMake(0, 0) midmargin:0];
    self.btn.text = SQNSLocalString(@"开始认证");
    self.btn.textColor = SQColor333333;
    self.btn.SQBackimageView.image = SQGetImage(@"按钮背景");
    self.btn.backgroundColor = SQColor(@"#CECECE");
    self.btn.SQBackimageView.hidden = YES;
    self.btn.SQBackimageView. contentMode = UIViewContentModeScaleAspectFill;
    self.btn.layer.cornerRadius = 22;
    self.btn.layer.masksToBounds = YES;
    [self.view addSubview:self.btn];
    [self.btn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.equalTo(self.view);
        make.width.mas_equalTo(SCREEN_WIDETH-48);
        make.height.mas_equalTo(44);
        make.bottom.equalTo(self.view.mas_bottom).offset(-FootHeight-20);
    }];

    [self.btn setTouchBlock:^(SQCustomButton * _Nonnull button) {
        [weakSelf SQ_KaiShiRenZheng];
    }];
    
    YYLabel * label3 = [[YYLabel alloc]initWithFrame:CGRectMake(SCREEN_WIDETH/2.f-70, SCREEN_HEIGHT- FootHeight-20, 160, 30)];
    label3.textVerticalAlignment = YYTextVerticalAlignmentCenter;
    label3.textAlignment = NSTextAlignmentCenter;
    label3.numberOfLines = 0;
    [self.view addSubview:label3];
    NSDictionary *attributes = @{NSFontAttributeName:FONT_MEDIUM(12) , NSForegroundColorAttributeName: SQColor(@"#DBDBDB")};
    NSMutableAttributedString *text = [[NSMutableAttributedString alloc] initWithString:SQNSLocalString(@"我已阅读并同意《隐私协议》") attributes:attributes];
   
    //设置高亮色和点击事件
    [text yy_setTextHighlightRange:[[text string] rangeOfString:SQNSLocalString(@"《隐私协议》")] color:SQColor(@"#FFFFFF") backgroundColor:[UIColor clearColor] tapAction:^(UIView * _Nonnull containerView, NSAttributedString * _Nonnull text, NSRange range, CGRect rect) {
        CommonWebVcView *vc= [[CommonWebVcView alloc]init];
        vc.urlStr =  YSTK;
        [weakSelf.navigationController pushViewController:vc animated:YES];
    }];
    NSRange range2=[[text string]rangeOfString:SQNSLocalString(@"《隐私协议》") ];
    YYTextDecoration* deco2=[YYTextDecoration decorationWithStyle:(YYTextLineStyleSingle) width:[NSNumber numberWithInt:0] color:[UIColor whiteColor]];
    [text yy_setTextUnderline:deco2 range:range2];
    label3.attributedText = text;
    
    SQCustomButton * leftbtn = [[SQCustomButton alloc]initType:SQCustomButtonLeftImageType imageSize:CGSizeMake(15, 15) midmargin:6];
    leftbtn.image = SQGetImage(@"选择");
    [self.view addSubview:leftbtn];
    [leftbtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerY.equalTo(label3);
        make.height.mas_equalTo(40);
        make.right.equalTo(label3.mas_left);
        make.width.mas_equalTo(40);
    }];
    
    [leftbtn setTouchBlock:^(SQCustomButton * _Nonnull button) {
        weakSelf.isXieyi = !weakSelf.isXieyi;
        if (weakSelf.isXieyi) {
            button.image = SQGetImage(@"未选择");
        } else {
            button.image = SQGetImage(@"选择");
        }
    }];
}

-(void)SQ_KaiShiRenZheng{

    if (self.isXieyi) {
        [YJProgressHUD showMsgWithoutView:SQNSLocalString(@"请查看并勾选协议")];
        return;
    }
    if (self.addImage.SQBackimageView.image ==nil) {
        [YJProgressHUD showMsgWithoutView:SQNSLocalString(@"请先按要求上传对应照片")];
        return;
    }
    WS(weakSelf);
    if ([self.imageUrl isNotEmpty]) {
        [self SQ_setUpName:self.imageUrl];
    }else{
        [YJProgressHUD SQ_showMsgWithoutView:@""];
        [HttpTool SQ_Image:self.addImage.SQBackimageView.image successBlock:^(BaseModel * _Nonnull httpModel) {
            [weakSelf SQ_setUpName:httpModel.data];
        } andFailBloc:^(BaseModel * _Nonnull httpModel, NSError * _Nullable error) {
            [YJProgressHUD showMsgWithoutView:httpModel.message];
        }];
     }
}
-(void)SQ_setUpName:(NSString*)header{
        if (![header isNotEmpty]) {
            [YJProgressHUD showMsgWithoutView:SQNSLocalString(@"头像上传错误")];
            return;
    }
    self.imageUrl = header;
    RealPopView * vc = [[RealPopView alloc]initWithFrame:CGRectMake(0, 0, SCREEN_WIDETH, SCREEN_HEIGHT)];
    LSTPopView * pop = [LSTPopView initWithCustomView:vc
                                           parentView:self.view
                                             popStyle:LSTPopStyleSmoothFromBottom dismissStyle:LSTDismissStyleSmoothToBottom];
    pop.hemStyle = LSTHemStyleBottom;
    pop.isAvoidKeyboard = NO;
    [pop pop];
    LSTPopViewWK(pop)
    WS(weakSelf);
    [vc.deteleBtn setTouchBlock:^(SQCustomButton * _Nonnull button) {
        [wk_pop dismiss];
    }];
  
    [vc setTicketBlock:^(NSString * _Nonnull urlString) {
        [wk_pop dismiss];
        if ([urlString isNotEmpty]) {
            [weakSelf SQ_certifyId:urlString];
        }
    }];
   
}
 
-(void)SQ_certifyId:(NSString*)certifyId{
    WS(weakSelf);
    [YJProgressHUD SQ_showMsgWithoutView:@""];
    NSMutableDictionary * dic = [[NSMutableDictionary alloc]init];
    [dic setObject:self.imageUrl forKey:@"portrait"];
    [dic setObject:certifyId forKey:@"url"];
    [HttpTool postJson:@"realAuth/save" paramDic:dic successBlock:^(BaseModel * _Nonnull httpModel) {
        UserModel * model = [UserModel share];
        model.realStatus = 0;
        [UserModel updateLocalUserModel:model];
        if (weakSelf.isInfo) {
            [weakSelf SQ_header];
        } else {
            [weakSelf SQ_popViewVC];
        }
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            [YJProgressHUD showMsgWithoutView:SQNSLocalString(@"认证资料提交成功,我们将在24小时内审核完成!")];
        });
    } andFailBloc:^(BaseModel * _Nonnull httpModel, NSError * _Nullable error) {
        [YJProgressHUD showMsgWithoutView:httpModel.message];
    }];
}
 
-(void)SQ_header{
    UINavigationController *nav = [[UINavigationController alloc] initWithRootViewController:[[ViewController alloc]init] ];
    self.view.window.rootViewController = nav;
}
 
-(void)SQ_addImageButtonClick{
    WS(weakSelf);
    _imagePickerVc = [[UIImagePickerController alloc] init];
    _imagePickerVc.delegate = self;
    _imagePickerVc.allowsEditing = YES;
    UIImagePickerControllerSourceType sourceType = UIImagePickerControllerSourceTypeCamera;
    if ([UIImagePickerController isSourceTypeAvailable: sourceType]) {
        weakSelf.imagePickerVc.sourceType = sourceType;
        if ([UIImagePickerController isCameraDeviceAvailable:UIImagePickerControllerCameraDeviceFront])
            {
            _imagePickerVc.cameraDevice = UIImagePickerControllerCameraDeviceFront;
            }
        [self presentViewController:weakSelf.imagePickerVc animated:YES completion:nil];
    } else {
        NSLog(@"模拟器中无法打开照相机,请在真机中使用");
    }
}

- (void)imagePickerController:(UIImagePickerController*)picker didFinishPickingMediaWithInfo:(NSDictionary *)info {
    [picker dismissViewControllerAnimated:YES completion:nil];
    WS(weakSelf);
    NSString *type = [info objectForKey:UIImagePickerControllerMediaType];
    if ([type isEqualToString:@"public.image"]) {
        UIImage *photo = [info objectForKey:UIImagePickerControllerEditedImage];
        if (photo == nil)
            {
                photo = [info objectForKey:UIImagePickerControllerOriginalImage];
            }
        [weakSelf SQ_caijian:photo];
    }else
    {
        [YJProgressHUD showMsgWithoutView:SQNSLocalString(@"相册数据异常")];
    }
}
//上传相册
-(void)SQ_caijian:(UIImage*)image {
   
    self.addImage.SQBackimageView.image = image;
    self.addImage.imageView.hidden = YES;
    self.btn.SQBackimageView.hidden = NO;
    self.btn.textColor = UIColor.whiteColor;
    self.imageUrl = nil;
}

#pragma mark UICollectionViewDelegate,UICollectionViewDataSource
-(NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section{
    return 3;
}

-(UICollectionViewCell *)collectionView:(UICollectionView*)collectionView cellForItemAtIndexPath:(nonnull NSIndexPath *)indexPath{
    RealCollectionViewCell * cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"RealCollectionViewCell" forIndexPath:indexPath];
    if (indexPath.item==0) {
        cell.headerLabel.image = SQGetImage(@"正式穿着");
        cell.nameLabel.text = SQNSLocalString(@"正式穿着");
    } else if (indexPath.item==1){
        cell.headerLabel.image = SQGetImage(@"面对镜头");
        cell.nameLabel.text = SQNSLocalString(@"面对镜头");
    } else if (indexPath.item==2){
        cell.headerLabel.image = SQGetImage(@"面带微笑");
        cell.nameLabel.text = SQNSLocalString(@"面带微笑");
    }
    return cell;
}

- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath {
    CGFloat w = SCREEN_WIDETH/2.f;
    return CGSizeMake(w, 250);
}

- (CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout minimumLineSpacingForSectionAtIndex:(NSInteger)section{
    return 0;
}

- (CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout minimumInteritemSpacingForSectionAtIndex:(NSInteger)section{
    return 0;
}

- (UIEdgeInsets)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout insetForSectionAtIndex:(NSInteger)section{
    return UIEdgeInsetsMake(0, 0, 0, 0);
}
- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath{
    [self.collectionView scrollToItemAtIndexPath:indexPath atScrollPosition:UICollectionViewScrollPositionCenteredHorizontally animated:YES];

}


- (SQCustomButton *)addImage{
    if (!_addImage) {
        _addImage = [[SQCustomButton alloc]initType:SQCustomButtonTopImageType imageSize:CGSizeMake(SCREEN_WIDETH-120, SCREEN_HEIGHT-FootHeight-120-10-250-TopHeight) midmargin:0];
        _addImage.imageView.contentMode = UIViewContentModeScaleAspectFill;
        _addImage.SQBackimageView.contentMode = UIViewContentModeScaleAspectFill;
        _addImage.layer.cornerRadius = 12;
        _addImage.clipsToBounds = YES;
        _addImage.image = SQGetImage(@"上传图片 1");
    }
    return _addImage;
}

@end
